<template>
  <div class="pane-account">
    <el-form
      :model="account"
      :rules="accountRules"
      status-icon
      label-width="60px"
      style="max-width: 460px"
      ref="formRef"
    >
      <el-form-item label="帐号" size="large" prop="userAccount">
        <el-input v-model="account.userAccount" />
      </el-form-item>
      <el-form-item label="密码" size="large" prop="userPwd">
        <el-input v-model="account.userPwd" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue"
import type { FormInstance, FormRules } from "element-plus"
import { ElMessage } from "element-plus"
// 针对某些组件引入样式
// import "element-plus/theme-chalk/el-message.css"
import useLoginStore from "@/store/login/login"
import type { IAccount } from "@/types"
import { localCache } from "@/utils/cacheData"
import { CACHE_ACCOUNT, CACHE_PASSWORD } from "@/global/constants"

// 1.定义account数据
const account = reactive<IAccount>({
  userAccount: localCache.getCache(CACHE_ACCOUNT) ?? "",
  userPwd: localCache.getCache(CACHE_PASSWORD) ?? ""
})

// 2.定义校验规则
const accountRules: FormRules = {
  userAccount: [
    { required: true, message: "必须输入帐号信息", trigger: "blur" },
    // { min: 6, max: 18, required: true, message: "账号长度需在6-18位之间", trigger: "blur" }
    // 复杂校验规制可以写一个正则
    {
      pattern: /^[a-zA-Z0-9_-]{4,12}$/,
      required: true,
      message: "账号格式应为4-12位的数字字母下划线组成",
      trigger: "blur"
    }
  ],
  userPwd: [
    { required: true, message: "必须输入密码信息", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_-]{6,18}$/,
      required: true,
      message: "账号格式应为6-18位的数字字母下划线组成",
      trigger: "blur"
    }
  ]
}

// 3.执行账号登录逻辑
const formRef = ref<FormInstance>()
const loginStore = useLoginStore()
function loginAction(keepPwd: boolean) {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 1.获取用户输入的账号和密码
      const userAccount = account.userAccount
      const userPwd = account.userPwd
      // 2.发送请求
      loginStore.loginAccountAction({ userAccount, userPwd }, keepPwd).then(() => {
        // 路由跳转 （main页面中）也可以放到这个位置

        ElMessage({
          message: "登录成功!",
          type: "success"
        })
      })
    } else {
      ElMessage.error("请检查提交的内容，输入正确的格式！")
      return false
    }
  })
}
/*
  通过模板ref或者$parent链获取到的组件实例不会暴露任何在<script setup>中声明的绑定
  通过defineExpose编译器宏来显式指定在<script setup>组件中要暴露出去的property
 */
defineExpose({
  loginAction
})
</script>

<style lang="less" scoped></style>
